﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime,json
from .login.login import *
from .setting import *

from flask_cors import CORS
user_blue = Blueprint('user',__name__)

@login_blue.route('/sys/second')
# @login_required
def secondPage():
	# print(dir(current_user))
	# print(current_user.get_id())
	# print(current_user.username)
	# print(current_user.password)
	returnData = {'code': 0, 'msg': 'success', 'data': 'second Blood(来自 id: ' + str(current_user.get_id())+' username:'+current_user.username+' password:'+current_user.password +')' }
	return json.dumps(returnData)
  
def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@user_blue.route('/sys/user/list')
# @login_required
def userlist():
	if request.args.get('username'):like = request.args.get('username')
	else:like=''
	if request.args.get('page'):page = request.args.get('page')
	else:page=1
	if request.args.get('limit'):limit = request.args.get('limit')
	else:limit=10
	print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_user WHERE  username LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sqlcount = "SELECT count(*) from sys_user  WHERE  username LIKE '%"+like+"%'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			# print(dataList1[i])
			# dataList.append({'userId':dataList1[i][0],'username':dataList1[i][1],'password':dataList1[i][2],'salt':dataList1[i][3],'email':dataList1[i][4],'mobile':dataList1[i][5],'status':dataList1[i][6],'create_user_id':dataList1[i][7],'create_time':dataList1[i][8]})
			dataList.append({'userId':dataList1[i][0],'username':dataList1[i][1],'password':dataList1[i][2],'email':dataList1[i][4],'mobile':dataList1[i][5],'status':dataList1[i][6],'createUserId':dataList1[i][7],'createTime':dataList1[i][8]})
		# print(dataList)
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
	except Exception as e:
		return "Error: unable to fetch data from sys_user"+str(e)
	db.close()
	data={
			'msg': 'success',
			'code': 0,
			'page': {
				'totalCount': len(dataList),
				'pageSize': 10,
				'totalPage': 1,
				'currPage': 1,
				'list': dataList
				}
			}
	return json.dumps(data,default=json_encoder)
@user_blue.route('/sys/user/save',methods=['POST'])
# @login_required
def usersave():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		# if 'user_id' in d.keys():user_id = d['user_id']
		# else:user_id=''
		if 'username' in d.keys():username = d['username']
		else:username=''
		if 'password' in d.keys():password = d['password']
		else:password=''
		if 'salt' in d.keys():salt = d['salt']
		else:salt=''
		if 'email' in d.keys():email = d['email']
		else:email=''
		if 'mobile' in d.keys():mobile = d['mobile']
		else:mobile=''
		if 'status' in d.keys():status = d['status']
		else:status=''
		if 'createUserId' in d.keys():createUserId = d['createUserId']
		else:createUserId=''
		if 'createTime' in d.keys():createTime = d['createTime']
		else:createTime=''
	elif request.form:
		# user_id = request.form['user_id']
		username = request.form['username']
		password = request.form['password']
		salt = request.form['salt']
		email = request.form['email']
		mobile = request.form['mobile']
		status = request.form['status']
		createUserId = request.form['createUserId']
		createTime = request.form['createTime']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = '''insert into sys_user (username,password,salt,email,mobile,status,create_user_id,create_time) values('''+"'"+str(username)+"','"+str(password)+"','"+str(salt)+"','"+str(email)+"','"+str(mobile)+"','"+str(status)+"','"+str(createUserId)+"','"+str(createTime)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from sys_user"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@user_blue.route('/sys/user/update',methods=['POST'])
# @login_required
def userupdate():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'userId' in d.keys():userId = d['userId']
		else:userId=''
		if 'username' in d.keys():username = d['username']
		else:username=''
		if 'password' in d.keys():password = d['password']
		else:password=''
		if 'salt' in d.keys():salt = d['salt']
		else:salt=''
		if 'email' in d.keys():email = d['email']
		else:email=''
		if 'mobile' in d.keys():mobile = d['mobile']
		else:mobile=''
		if 'status' in d.keys():status = d['status']
		else:status=''
		if 'createUserId' in d.keys():createUserId = d['createUserId']
		else:createUserId=''
		if 'createTime' in d.keys():createTime = d['createTime']
		else:createTime=''
	elif request.form:
		userId = request.form['userId']
		username = request.form['username']
		password = request.form['password']
		salt = request.form['salt']
		email = request.form['email']
		mobile = request.form['mobile']
		status = request.form['status']
		createUserId = request.form['createUserId']
		createTime = request.form['createTime']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	cursor = db.cursor()
	sql = "UPDATE sys_user SET username='"+str(username)+"',password='"+str(password)+"',salt='"+str(salt)+"',email='"+str(email)+"',mobile='"+str(mobile)+"',status='"+str(status)+"',create_user_id='"+str(createUserId)+"',create_time='"+str(createTime)+"'  WHERE user_id = '"+str(userId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_user"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@user_blue.route('/sys/user/delete',methods=['POST'])
# @login_required
def userdelete():
	# print("content_type:", request.headers.get("content_type"))
	# print("data:", request.data)
	# print("data:", str(request.data, 'UTF-8'))
	# print("form:", request.form)
	# print("files:", request.files)
	if request.data:
		d=json.loads(str(request.data, 'UTF-8'))
		userId = d['userId']
	elif request.form:
		userId = request.form['userId']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "DELETE FROM sys_user WHERE user_id = '"+str(userId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_user"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@user_blue.route('/sys/user/info')
# @login_required
def userinfo():
	# print(dir(current_user))
	# print(current_user.get_id())
	# print(current_user.username)
	# print(current_user.password)
	# return {"code":0,"user":{'username':'admin','password':'admin',"userId":'1'}}
	return {"code":0,"user":{'username':current_user.username,'password':current_user.password,"userId":str(current_user.get_id())}}
@user_blue.route('/sys/user/info/<id>')
# @login_required
def userinfobyid(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_user where  user_id = '"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		print(dataList1)
		user={'userId':dataList1[0][0],'username':dataList1[0][1],'password':dataList1[0][2],'email':dataList1[0][4],'mobile':dataList1[0][5],'status':dataList1[0][6],'create_user_id':dataList1[0][7],'create_time':dataList1[0][8]}
		data={
				'msg': 'success',
				'code': 0,
				'user': user
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_user"+str(e)
	db.close()
@user_blue.route('/sys/user/select')
# @login_required
def userselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_user"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		for row in dataList1:
			print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'userId':dataList1[i][0],'username':dataList1[i][1],'password':dataList1[i][2],'email':dataList1[i][4],'mobile':dataList1[i][5],'status':dataList1[i][6],'createUserId':dataList1[i][7],'createTime':dataList1[i][8]})
		# print(dataList)
		data={
				'msg': 'success',
				'code': 0,
				'list': dataList
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()	
	
	
	
@user_blue.route('/sys/user/password')
# @login_required
def userpassword():
     return '''<h1>aa</h1>
<br/>
'''  	


